﻿namespace CatClient.Message.Spi.Internals
{
    using CatClient.Util;
    using System;
    using System.Diagnostics;
    using System.Text;
    using System.Threading;

    public class MessageIdFactory
    {
        private string _domain;
        private int _index;
        private string _ipAddress;
        private long _lastTimestamp;
        private static readonly int ProcessId = Process.GetCurrentProcess().Id;

        public MessageIdFactory()
        {
            this._lastTimestamp = this.Timestamp;
        }

        public string GetNextId()
        {
            long timestamp = this.Timestamp;
            if (timestamp != this._lastTimestamp)
            {
                Interlocked.Exchange(ref this._index, 0);
                Interlocked.Exchange(ref this._lastTimestamp, timestamp);
            }
            int num2 = Interlocked.Increment(ref this._index);
            StringBuilder builder1 = new StringBuilder(this._domain.Length + 0x20);
            builder1.Append(this._domain);
            builder1.Append('-');
            builder1.Append(this._ipAddress);
            //builder1.Append('_');
            //builder1.Append(ProcessId);
            builder1.Append('-');
            builder1.Append(timestamp);
            builder1.Append('-');
            builder1.Append(num2);
            return builder1.ToString();
        }

        internal void Initialize(string domain)
        {
            this._domain = domain;
            if (this._ipAddress == null)
            {
                StringBuilder builder = new StringBuilder();
                foreach (byte num2 in NetworkInterfaceManager.GetAddressBytes())
                {
                    int num3 = (num2 >> 4) & 15;
                    builder.Append(num3.ToString("x"));
                    builder.Append((num2 & 15).ToString("x"));
                }
                this._ipAddress = builder.ToString();
            }
        }

        protected internal long Timestamp =>
            MilliSecondTimer.CurrentTimeHoursForJava;

        public string Domain
        {
            set
            {
                this._domain = value;
            }
        }

        public string IpAddress
        {
            set
            {
                this._ipAddress = value;
            }
        }
    }
}

